from flask import Blueprint
from flask import request, current_app
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from shared import db, bcrypt
from http_status import HttpStatus
import utils
from models import User

users_bp = Blueprint('users', __name__)

@users_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    account = data.get('account')
    password = data.get('password')
    nickname = data.get('nickname')
    avatar = data.get('avatar')
    sex = data.get('sex')

    if not account or not password or not nickname or not avatar or not sex:
        return utils.response(success=False, message='参数错误！', status=HttpStatus.CODE_PARAM_ERROR)

    if User.query.filter_by(account=account).first():
        return utils.response(success=False, message='用户已存在！', status=HttpStatus.CODE_USER_EXIST)
    
    hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
    new_user = User(
        account=account, 
        password=hashed_password, 
        nickname=nickname, 
        avatar=avatar,
        sex=sex,
        birthday='2000-01-01',
        signature='这家伙很懒！没有签名~'
    )
    db.session.add(new_user)
    db.session.commit()

    return utils.response(success=True, data=[], message='注册成功！', status=HttpStatus.CODE_SUECCESS)

@users_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    account = data.get('account')
    password = data.get('password')

    user = User.query.filter_by(account=account).first()
    if not user or not bcrypt.check_password_hash(user.password, password):
        return utils.response(success=False, message='登录失败！账号密码错误~', status=HttpStatus.CODE_USER_PASSWORD_ERROR)

    user_info = {
            'id': user.id,
            'avatar': user.avatar,
            'account': user.account,
            'nickname': user.nickname,
            'sex': user.sex,
            'signature': user.signature,
            'birthday': user.birthday,
    }
    
    access_token = create_access_token(identity=str(user.id))
    refresh_token = create_refresh_token(identity=str(user.id))

    expiration_str = utils.expiration_str(current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])
    
    res_data = {
        'accessToken': access_token,
        'refreshToken': refresh_token,
        'user': user_info,
        'expires': expiration_str
    }

    return utils.response(success=True, data=res_data, message='登录成功！', status=HttpStatus.CODE_SUECCESS)

@users_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True) 
def refresh():
    refresh_token = request.headers.get('Authorization').split()[1]
    current_user = get_jwt_identity()
    new_access_token = create_access_token(identity=str(current_user.id))

    expiration_str = utils.expiration_str(current_app.config['JWT_ACCESS_TOKEN_EXPIRES'])

    res_data = {
        'accessToken': new_access_token,
        'refreshToken': refresh_token,
        'user': current_user,
        'expires': expiration_str
    }

    return utils.response(success=True, data=res_data, message='更新获取token成功！', status=HttpStatus.CODE_SUECCESS)


@users_bp.route('/getUserInfo', methods=['GET'])
@jwt_required()
def get_user_info():
    user_id =  get_jwt_identity()
    user = User.query.filter_by(id=user_id).first()
    return utils.response(success=True, data=user.to_dict(), message='获取用户信息成功！', status=HttpStatus.CODE_SUECCESS)

@users_bp.route('/modify', methods=['POST'])
@jwt_required()
def modify():
    user_id =  get_jwt_identity()
    user = User.query.filter_by(id=user_id).first()
    if not user:
        return utils.response(success=False, message='用户不存在！', status=HttpStatus.CODE_USER_NOT_EXIST)
    
    data = request.get_json()
    nickname = data.get('nickname', '')
    avatar = data.get('avatar', '')
    password = data.get('password', '')
    sex = data.get('sex', 1)
    # birthday = data.get('birthday', '1971-01-01')
    birthday = data.get('birthday', '').split('T')[0]
    signature = data.get('signature', '这家伙很懒！没有签名~')
    if not nickname or not avatar or not password or not sex or not birthday or not signature:
        return utils.response(success=False, message='参数错误！', status=HttpStatus.CODE_PARAM_ERROR)

    user.nickname = nickname
    user.avatar = avatar
    user.password = bcrypt.generate_password_hash(password).decode('utf-8')
    user.sex = sex
    user.birthday = birthday
    user.signature = signature
    
    db.session.commit()
    return utils.response(success=True, data=[], message='修改成功！', status=HttpStatus.CODE_SUECCESS)

@users_bp.route('/update', methods=['POST'])
@jwt_required()
def update():
    user_id =  get_jwt_identity()
    user = User.query.filter_by(id=user_id).first()
    if not user:
        return utils.response(success=False, message='用户不存在！', status=HttpStatus.CODE_USER_NOT_EXIST)
    
    data = request.get_json()
    nickname = data.get('nickname', '')
    avatar = data.get('avatar', '')
    password = data.get('password', '')
    sex = data.get('sex', 1)
    birthday = data.get('birthday', '').split('T')[0]
    signature = data.get('signature', '这家伙很懒！没有签名~')

    if nickname !='':
        user.nickname = nickname
    if avatar !='':
        user.avatar = avatar
    if password !='':
        user.password = bcrypt.generate_password_hash(password).decode('utf-8')
    user.sex = sex
    if birthday !='':
        user.birthday = birthday
    if signature !='':
        user.signature = signature
    
    if nickname != '' or avatar != '' or password != '':
        db.session.commit()

    user_info = {
            'id': user.id,
            'avatar': user.avatar,
            'account': user.account,
            'nickname': user.nickname,
            'sex': user.sex,
            'signature': user.signature,
            'birthday': user.birthday,
    }

    return utils.response(success=True, data={'user': user_info}, message='修改成功！', status=HttpStatus.CODE_SUECCESS)

@users_bp.route('/verifyPassword', methods=['POST'])
@jwt_required()
def verify_password():
    user_id =  get_jwt_identity()
    user = User.query.filter_by(id=user_id).first()
    if not user:
        return utils.response(success=False, message='用户不存在！', status=HttpStatus.CODE_USER_NOT_EXIST)
    
    data = request.get_json()
    password = data.get('password', '')
    if not password:
        return utils.response(success=False, message='参数错误！', status=HttpStatus.CODE_PARAM_ERROR)
    
    if bcrypt.check_password_hash(user.password, password):
        return utils.response(success=True, data=[], message='密码验证成功！', status=HttpStatus.CODE_SUECCESS)
    else:
        return utils.response(success=False, message='密码验证失败！', status=HttpStatus.CODE_USER_PASSWORD_ERROR)
    